﻿@model Material.Mvc.Models.WeatherViewModel
@{
    ViewData["Title"] = "天气查询";
}

<div class="weather-container">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1><i class="fas fa-cloud-sun"></i> 天气查询系统</h1>
        <p>查询全球任意位置的天气信息，支持三天预报</p>
    </div>

    <div class="row">
        <!-- 左侧：天气查询区域 -->
        <div class="col-lg-8">
            <!-- 单个查询框 -->
            <div class="weather-card">
                <div class="card-header">
                    <h3><i class="fas fa-search"></i> 天气查询</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="latitude">纬度</label>
                                <input type="number" id="latitude" class="form-control" placeholder="例如: 31.2304" step="0.0001" value="@Model.Latitude">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="longitude">经度</label>
                                <input type="number" id="longitude" class="form-control" placeholder="例如: 121.4737" step="0.0001" value="@Model.Longitude">
                            </div>
                        </div>
                                                 <div class="col-md-4">
                             <div class="form-group">
                                 <label for="locationName">位置名称</label>
                                 <input type="text" id="locationName" class="form-control" placeholder="输入经纬度后自动获取">
                                 <small class="form-text text-muted">输入经纬度后将自动获取地区名称</small>
                             </div>
                         </div>
                    </div>
                                         <div class="row mt-3">
                         <div class="col-md-4">
                             <button type="button" id="queryWeather" class="btn btn-primary btn-lg btn-block">
                                 <i class="fas fa-search"></i> 查询天气
                             </button>
                         </div>
                         <div class="col-md-4">
                             <button type="button" id="saveLocation" class="btn btn-success btn-lg btn-block">
                                 <i class="fas fa-save"></i> 保存位置
                             </button>
                         </div>
                         <div class="col-md-4">
                             <button type="button" id="batchQueryWeather" class="btn btn-info btn-lg btn-block">
                                 <i class="fas fa-list"></i> 批量查询
                             </button>
                         </div>
                     </div>
                </div>
            </div>

            <!-- 天气显示区域 -->
            <div id="weatherDisplay" class="weather-card mt-4" style="display: none;">
                <div class="card-header">
                    <h3><i class="fas fa-cloud"></i> 天气信息</h3>
                    <span id="currentLocation" class="location-badge"></span>
                </div>
                <div class="card-body">
                    <!-- 当前天气 -->
                    <div id="currentWeather" class="current-weather-section"></div>
                    
                    <!-- 三天预报 -->
                    <div class="forecast-section">
                        <h4><i class="fas fa-calendar-alt"></i> 三天预报</h4>
                        <div id="forecastContainer" class="forecast-container"></div>
                    </div>
                </div>
            </div>

                         <!-- 加载状态 -->
             <div id="loadingIndicator" class="loading-container" style="display: none;">
                 <div class="spinner-border text-primary" role="status">
                     <span class="sr-only">加载中...</span>
                 </div>
                 <p class="mt-2">正在获取天气数据...</p>
             </div>

             
        </div>

        <!-- 右侧：位置管理区域 -->
        <div class="col-lg-4">
                         <!-- 保存的位置 -->
             <div class="weather-card">
                 <div class="card-header">
                     <h3><i class="fas fa-map-marker-alt"></i> 保存的位置</h3>
                 </div>
                 <div class="card-body">
                     <div id="savedLocations">
                         @if (Model.SavedLocations.Any())
                         {
                             foreach (var location in Model.SavedLocations)
                             {
                                 <div class="location-item" data-id="@location.Id">
                                     <div class="location-info">
                                         <h5>@location.Name</h5>
                                         <p class="coordinates">@location.Latitude.ToString("F4"), @location.Longitude.ToString("F4")</p>
                                         <small class="text-muted">@location.CreatedAt.ToString("yyyy-MM-dd")</small>
                                     </div>
                                     <div class="location-actions">
                                         <button class="btn btn-sm btn-outline-primary use-location" 
                                                 data-lat="@location.Latitude" 
                                                 data-lng="@location.Longitude" 
                                                 data-name="@location.Name">
                                             <i class="fas fa-search"></i>
                                         </button>
                                         <button class="btn btn-sm btn-outline-danger delete-location" data-id="@location.Id">
                                             <i class="fas fa-trash"></i>
                                         </button>
                                     </div>
                                 </div>
                             }
                         }
                         else
                         {
                             <p class="text-muted">暂无保存的位置</p>
                         }
                     </div>
                 </div>
             </div>

             <!-- 批量查询天气区域（缩小版） -->
             <div id="batchQueryWeatherArea" class="weather-card mt-3" style="display: none;">
                 <div class="card-header">
                     <h4><i class="fas fa-list"></i> 批量查询</h4>
                 </div>
                 <div class="card-body">
                     <div class="batch-input-area">
                         <div class="form-group">
                             <label class="small">输入多个位置坐标</label>
                             <textarea id="batchCoordinates" class="form-control" rows="4" 
                                       placeholder="纬度,经度,名称
例如：31.2304,121.4737,上海"></textarea>
                             <small class="form-text text-muted">每行：纬度,经度,名称</small>
                         </div>
                         <div class="d-grid gap-2">
                             <button type="button" id="startBatchQuery" class="btn btn-info btn-sm">
                                 <i class="fas fa-play"></i> 开始查询
                             </button>
                             <button type="button" id="clearBatchResults" class="btn btn-secondary btn-sm">
                                 <i class="fas fa-trash"></i> 清空
                             </button>
                         </div>
                     </div>
                     
                     <!-- 批量查询结果 -->
                     <div id="batchResults" class="batch-results mt-3" style="display: none;">
                         <h6><i class="fas fa-chart-bar"></i> 查询结果</h6>
                         <div id="batchResultsContainer"></div>
                     </div>
                 </div>
             </div>


        </div>
    </div>
</div>

<!-- 消息提示 -->
<div id="messageToast" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1055;">
    <div id="messageToastContent" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <strong class="me-auto" id="toastTitle">消息</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage">
        </div>
    </div>
</div>

@section Styles {
    <style>
        .weather-container {
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .page-header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .page-header h1 {
            font-size: 2.5rem;
            font-weight: 300;
            margin-bottom: 10px;
        }

        .page-header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .weather-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border: none;
        }

        .card-header h3 {
            margin: 0;
            font-size: 1.3rem;
            font-weight: 500;
        }

        .card-body {
            padding: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }

        .form-control {
            border-radius: 8px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }

        .btn {
            border-radius: 8px;
            padding: 12px 20px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }

        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            border: none;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
            border: none;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .location-badge {
            background: rgba(255,255,255,0.2);
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
        }

        .current-weather-section {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 25px;
            text-align: center;
        }

        .current-temp {
            margin-bottom: 20px;
        }

        .temp-value {
            font-size: 3rem;
            font-weight: 700;
            display: block;
            margin-bottom: 10px;
        }

        .temp-details p {
            margin: 5px 0;
            font-size: 1.1rem;
        }

        .current-details {
            margin-top: 20px;
        }

        .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }

        .current-details .detail-item {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            text-align: center;
            padding: 10px;
            border-radius: 8px;
        }

        .current-details .detail-label {
            color: rgba(255,255,255,0.8);
            font-size: 0.8rem;
            display: block;
            margin-bottom: 5px;
        }

        .current-details .detail-value {
            color: white;
            font-weight: 600;
            font-size: 1rem;
        }

        .forecast-section h4 {
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .forecast-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .forecast-item {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            border-left: 4px solid #667eea;
        }

        .forecast-date {
            font-weight: 600;
            color: #667eea;
            margin-bottom: 15px;
        }

        .forecast-temp {
            font-size: 2rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 10px;
        }

        .forecast-weather {
            font-size: 1.1rem;
            color: #666;
            margin-bottom: 15px;
        }

        .forecast-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            font-size: 0.9rem;
        }

        .detail-item {
            background: white;
            padding: 8px;
            border-radius: 6px;
            border: 1px solid #e9ecef;
        }

        .detail-label {
            color: #666;
            font-size: 0.8rem;
        }

        .detail-value {
            color: #333;
            font-weight: 600;
        }

        .location-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 10px;
            background: #f8f9fa;
        }

        .location-info h5 {
            margin: 0 0 5px 0;
            color: #333;
            font-size: 1rem;
        }

        .coordinates {
            margin: 0 0 5px 0;
            color: #666;
            font-size: 0.9rem;
        }

        .location-actions {
            display: flex;
            gap: 5px;
        }

        .loading-container {
            text-align: center;
            padding: 40px;
            color: #667eea;
        }

        .toast-container {
            z-index: 1055;
        }

        .toast {
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .batch-input-area textarea {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
        }

        .batch-results h4 {
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .batch-location-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #17a2b8;
        }

        .batch-location-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .batch-location-name {
            font-weight: 600;
            color: #17a2b8;
            font-size: 1.1rem;
        }

        .batch-location-coords {
            color: #666;
            font-size: 0.9rem;
        }

        .batch-weather-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .batch-weather-item {
            background: white;
            padding: 12px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #e9ecef;
        }

        .batch-weather-label {
            color: #666;
            font-size: 0.8rem;
            margin-bottom: 5px;
        }

        .batch-weather-value {
            color: #333;
            font-weight: 600;
            font-size: 1rem;
        }

        /* 缩小版批量查询样式 */
        #batchQueryWeatherArea .card-header h4 {
            font-size: 1.1rem;
            margin: 0;
        }

        #batchQueryWeatherArea .card-body {
            padding: 15px;
        }

        #batchQueryWeatherArea .form-group {
            margin-bottom: 15px;
        }

        #batchQueryWeatherArea .form-group label {
            font-size: 0.9rem;
            margin-bottom: 5px;
        }

        #batchQueryWeatherArea textarea {
            font-size: 0.8rem;
            padding: 8px 10px;
        }

        #batchQueryWeatherArea .btn {
            padding: 8px 12px;
            font-size: 0.85rem;
        }

        #batchQueryWeatherArea .batch-results h6 {
            font-size: 0.95rem;
            margin-bottom: 15px;
            color: #333;
        }

        #batchQueryWeatherArea .batch-location-card {
            padding: 12px;
            margin-bottom: 10px;
        }

        #batchQueryWeatherArea .batch-location-header {
            margin-bottom: 10px;
        }

        #batchQueryWeatherArea .batch-location-name {
            font-size: 0.9rem;
        }

        #batchQueryWeatherArea .batch-location-coords {
            font-size: 0.8rem;
        }

        #batchQueryWeatherArea .batch-weather-summary {
            gap: 8px;
            margin-top: 10px;
        }

        #batchQueryWeatherArea .batch-weather-item {
            padding: 8px;
        }

        #batchQueryWeatherArea .batch-weather-label {
            font-size: 0.75rem;
        }

        #batchQueryWeatherArea .batch-weather-value {
            font-size: 0.85rem;
        }

        /* 移动端响应式设计 */
        @@media (max-width: 768px) {
            .weather-container { 
                padding: 10px; 
            }
            .page-header h1 { 
                font-size: 2rem; 
            }
            .forecast-container { 
                grid-template-columns: 1fr; 
            }
            .detail-grid { 
                grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); 
            }
            .card-body { 
                padding: 15px; 
            }
        }
    </style>
}

@section Scripts {
    <script>
        $(document).ready(function() {
            // 查询天气
            $('#queryWeather').click(function() {
                const latitude = parseFloat($('#latitude').val());
                const longitude = parseFloat($('#longitude').val());
                
                if (!latitude || !longitude) {
                    showMessage('请输入有效的经纬度', 'error');
                    return;
                }
                
                queryWeather(latitude, longitude);
            });

            // 保存位置
            $('#saveLocation').click(function() {
                const latitude = parseFloat($('#latitude').val());
                const longitude = parseFloat($('#longitude').val());
                const name = $('#locationName').val().trim();
                
                if (!latitude || !longitude) {
                    showMessage('请输入有效的经纬度', 'error');
                    return;
                }
                
                if (!name) {
                    showMessage('请输入位置名称', 'error');
                    return;
                }
                
                saveLocation(latitude, longitude, name);
            });

            // 使用保存的位置
            $(document).on('click', '.use-location', function() {
                const lat = parseFloat($(this).data('lat'));
                const lng = parseFloat($(this).data('lng'));
                const name = $(this).data('name');
                
                $('#latitude').val(lat);
                $('#longitude').val(lng);
                $('#locationName').val(name);
                
                queryWeather(lat, lng);
            });

            // 删除单个位置
            $(document).on('click', '.delete-location', function() {
                const id = $(this).data('id');
                if (confirm('确定要删除这个位置吗？')) {
                    deleteLocation(id);
                }
            });

                         // 经纬度输入框变化时自动获取地区名称
             $('#latitude, #longitude').on('input', function() {
                 const latitude = parseFloat($('#latitude').val());
                 const longitude = parseFloat($('#longitude').val());
                 
                 if (latitude && longitude) {
                     // 延迟500ms避免频繁请求
                     clearTimeout(window.locationNameTimeout);
                     window.locationNameTimeout = setTimeout(() => {
                         getLocationName(latitude, longitude);
                     }, 500);
                 }
             });

             // 批量查询天气按钮
             $('#batchQueryWeather').click(function() {
                 $('#batchQueryWeatherArea').toggle();
             });

             // 开始批量查询
             $('#startBatchQuery').click(function() {
                 const coordinatesText = $('#batchCoordinates').val().trim();
                 if (!coordinatesText) {
                     showMessage('请输入要查询的坐标', 'error');
                     return;
                 }
                 
                 const coordinates = parseBatchCoordinates(coordinatesText);
                 if (coordinates.length === 0) {
                     showMessage('坐标格式不正确，请检查输入', 'error');
                     return;
                 }
                 
                 startBatchWeatherQuery(coordinates);
             });

             // 清空批量查询结果
             $('#clearBatchResults').click(function() {
                 $('#batchResultsContainer').empty();
                 $('#batchResults').hide();
                 $('#batchCoordinates').val('');
             });

            // 查询天气函数
            function queryWeather(latitude, longitude) {
                showLoading(true);
                
                $.ajax({
                    url: '/Weather/GetWeather',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        latitude: latitude,
                        longitude: longitude
                    }),
                    success: function(response) {
                        if (response.success) {
                            displayWeather(response.data);
                            showMessage('天气数据获取成功', 'success');
                        } else {
                            showMessage(response.message || '获取天气数据失败', 'error');
                        }
                    },
                    error: function() {
                        showMessage('网络错误，请稍后重试', 'error');
                    },
                    complete: function() {
                        showLoading(false);
                    }
                });
            }

            // 保存位置函数
            function saveLocation(latitude, longitude, name) {
                $.ajax({
                    url: '/Weather/SaveLocation',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        latitude: latitude,
                        longitude: longitude,
                        name: name
                    }),
                    success: function(response) {
                        if (response.success) {
                            showMessage(response.message, 'success');
                            // 刷新页面以显示新保存的位置
                            setTimeout(() => location.reload(), 1500);
                        } else {
                            showMessage(response.message, 'error');
                        }
                    },
                    error: function() {
                        showMessage('保存位置失败', 'error');
                    }
                });
            }

            // 删除位置函数
            function deleteLocation(id) {
                $.ajax({
                    url: '/Weather/DeleteLocation',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ id: id }),
                    success: function(response) {
                                             if (response.success) {
                         showMessage(response.message, 'success');
                         $(`.location-item[data-id="${id}"]`).remove();
                         // 刷新页面以更新位置列表
                         setTimeout(() => location.reload(), 1500);
                     } else {
                         showMessage(response.message, 'error');
                     }
                    },
                    error: function() {
                        showMessage('删除位置失败', 'error');
                    }
                });
            }

                         // 根据经纬度获取地区名称
             function getLocationName(latitude, longitude) {
                 $.ajax({
                     url: '/Weather/GetLocationName',
                     type: 'POST',
                     contentType: 'application/json',
                     data: JSON.stringify({
                         latitude: latitude,
                         longitude: longitude
                     }),
                     success: function(response) {
                         if (response.success && response.locationName) {
                             $('#locationName').val(response.locationName);
                         }
                     },
                     error: function() {
                         // 静默失败，不影响用户体验
                     }
                 });
             }

             // 解析批量坐标输入
             function parseBatchCoordinates(text) {
                 const lines = text.split('\n').filter(line => line.trim());
                 const coordinates = [];
                 
                 for (let line of lines) {
                     const parts = line.split(',').map(part => part.trim());
                     if (parts.length >= 2) {
                         const lat = parseFloat(parts[0]);
                         const lng = parseFloat(parts[1]);
                         const name = parts[2] || '';
                         
                         if (!isNaN(lat) && !isNaN(lng)) {
                             coordinates.push({ latitude: lat, longitude: lng, name: name });
                         }
                     }
                 }
                 
                 return coordinates;
             }

             // 开始批量天气查询
             function startBatchWeatherQuery(coordinates) {
                 $('#batchResultsContainer').empty();
                 $('#batchResults').show();
                 
                 let completedCount = 0;
                 const totalCount = coordinates.length;
                 
                 coordinates.forEach((coord, index) => {
                     const locationName = coord.name || `位置${index + 1}`;
                     
                     // 创建结果卡片
                     const resultCard = $(`
                         <div class="batch-location-card" data-index="${index}">
                             <div class="batch-location-header">
                                 <div>
                                     <div class="batch-location-name">${locationName}</div>
                                     <div class="batch-location-coords">${coord.latitude.toFixed(4)}, ${coord.longitude.toFixed(4)}</div>
                                 </div>
                                 <div class="batch-weather-status">
                                     <span class="badge bg-warning">查询中...</span>
                                 </div>
                             </div>
                             <div class="batch-weather-content">
                                 <div class="text-center text-muted">
                                     <div class="spinner-border spinner-border-sm" role="status">
                                         <span class="sr-only">加载中...</span>
                                     </div>
                                     <p class="mt-2">正在获取天气数据...</p>
                                 </div>
                             </div>
                         </div>
                     `);
                     
                     $('#batchResultsContainer').append(resultCard);
                     
                     // 查询天气
                     $.ajax({
                         url: '/Weather/GetWeather',
                         type: 'POST',
                         contentType: 'application/json',
                         data: JSON.stringify({
                             latitude: coord.latitude,
                             longitude: coord.longitude
                         }),
                         success: function(response) {
                             if (response.success) {
                                 displayBatchWeatherResult(index, response.data, locationName);
                             } else {
                                 displayBatchWeatherError(index, response.message || '获取失败');
                             }
                         },
                         error: function() {
                             displayBatchWeatherError(index, '网络错误');
                         },
                         complete: function() {
                             completedCount++;
                             if (completedCount === totalCount) {
                                 showMessage(`批量查询完成，共查询 ${totalCount} 个位置`, 'success');
                             }
                         }
                     });
                 });
             }

             // 显示批量查询的天气结果
             function displayBatchWeatherResult(index, weatherData, locationName) {
                 const card = $(`.batch-location-card[data-index="${index}"]`);
                 const current = weatherData.current;
                 
                 card.find('.batch-weather-status').html('<span class="badge bg-success">查询成功</span>');
                 card.find('.batch-weather-content').html(`
                     <div class="batch-weather-summary">
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">温度</div>
                             <div class="batch-weather-value">${current.temperature}°C</div>
                         </div>
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">体感温度</div>
                             <div class="batch-weather-value">${current.feelsLike}°C</div>
                         </div>
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">天气</div>
                             <div class="batch-weather-value">${current.weather}</div>
                         </div>
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">湿度</div>
                             <div class="batch-weather-value">${current.humidity}%</div>
                         </div>
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">风向</div>
                             <div class="batch-weather-value">${current.windDirection}</div>
                         </div>
                         <div class="batch-weather-item">
                             <div class="batch-weather-label">风速</div>
                             <div class="batch-weather-value">${current.windSpeed} m/s</div>
                         </div>
                     </div>
                 `);
             }

             // 显示批量查询的错误
             function displayBatchWeatherError(index, errorMessage) {
                 const card = $(`.batch-location-card[data-index="${index}"]`);
                 
                 card.find('.batch-weather-status').html('<span class="badge bg-danger">查询失败</span>');
                 card.find('.batch-weather-content').html(`
                     <div class="text-center text-danger">
                         <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                         <p>${errorMessage}</p>
                     </div>
                 `);
             }

            // 显示天气数据
            function displayWeather(weatherData) {
                const location = weatherData.location || '未知位置';
                $('#currentLocation').text(location);
                
                // 显示当前天气
                if (weatherData.current) {
                    const current = weatherData.current;
                    $('#currentWeather').html(`
                        <div class="current-temp">
                            <span class="temp-value">${current.temperature}°C</span>
                            <div class="temp-details">
                                <p>体感温度: ${current.feelsLike}°C</p>
                                <p>天气: ${current.weather}</p>
                            </div>
                        </div>
                                                 <div class="current-details">
                             <div class="detail-grid">
                                 <div class="detail-item">
                                     <span class="detail-label">湿度</span>
                                     <span class="detail-value">${current.humidity || 0}%</span>
                                 </div>
                                 <div class="detail-item">
                                     <span class="detail-label">风向</span>
                                     <span class="detail-value">${current.windDirection || '未知'}</span>
                                 </div>
                                 <div class="detail-item">
                                     <span class="detail-label">风速</span>
                                     <span class="detail-value">${current.windSpeed || 0} m/s</span>
                                 </div>
                                 <div class="detail-item">
                                     <span class="detail-label">空气质量</span>
                                     <span class="detail-value">${current.airQuality || 0}</span>
                                 </div>
                                 <div class="detail-item">
                                     <span class="detail-label">紫外线</span>
                                     <span class="detail-value">${current.uvIndex || 0}</span>
                                 </div>
                                 <div class="detail-item">
                                     <span class="detail-label">气压</span>
                                     <span class="detail-value">${current.pressure || 0} hPa</span>
                                 </div>
                             </div>
                         </div>
                    `);
                }
                
                // 显示三天预报
                if (weatherData.forecasts && weatherData.forecasts.length > 0) {
                    let forecastHtml = '';
                    weatherData.forecasts.forEach(forecast => {
                        const date = new Date(forecast.date);
                        const dateStr = date.toLocaleDateString('zh-CN', { 
                            month: 'short', 
                            day: 'numeric',
                            weekday: 'short'
                        });
                        
                        forecastHtml += `
                            <div class="forecast-item">
                                <div class="forecast-date">${dateStr}</div>
                                <div class="forecast-temp">${forecast.temperature}°C</div>
                                <div class="forecast-weather">${forecast.weather}</div>
                                <div class="forecast-details">
                                                                         <div class="detail-item">
                                         <div class="detail-label">体感温度</div>
                                         <div class="detail-value">${forecast.feelsLike || 0}°C</div>
                                     </div>
                                     <div class="detail-item">
                                         <div class="detail-label">湿度</div>
                                         <div class="detail-value">${forecast.humidity || 0}%</div>
                                     </div>
                                     <div class="detail-item">
                                         <div class="detail-label">风向</div>
                                         <div class="detail-value">${forecast.windDirection || '未知'}</div>
                                     </div>
                                     <div class="detail-item">
                                         <div class="detail-label">风速</div>
                                         <div class="detail-value">${forecast.windSpeed || 0} m/s</div>
                                     </div>
                                     <div class="detail-item">
                                         <div class="detail-label">空气质量</div>
                                         <div class="detail-value">${forecast.airQuality || 0}</div>
                                     </div>
                                     <div class="detail-item">
                                         <div class="detail-label">紫外线</div>
                                         <div class="detail-value">${forecast.uvIndex || 0}</div>
                                     </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    $('#forecastContainer').html(forecastHtml);
                }
                
                $('#weatherDisplay').show();
            }

            // 显示/隐藏加载状态
            function showLoading(show) {
                if (show) {
                    $('#loadingIndicator').show();
                    $('#weatherDisplay').hide();
                } else {
                    $('#loadingIndicator').hide();
                }
            }



            // 显示消息提示
            function showMessage(message, type = 'info') {
                const toast = $('#messageToastContent');
                const title = $('#toastTitle');
                const body = $('#toastMessage');
                
                title.text(type === 'error' ? '错误' : type === 'success' ? '成功' : '信息');
                body.text(message);
                
                if (type === 'error') {
                    toast.removeClass('bg-success bg-info').addClass('bg-danger text-white');
                } else if (type === 'success') {
                    toast.removeClass('bg-danger bg-info').addClass('bg-success text-white');
                } else {
                    toast.removeClass('bg-danger bg-success').addClass('bg-info text-white');
                }
                
                const bsToast = new bootstrap.Toast(toast);
                bsToast.show();
            }
        });
    </script>
}
